<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
use app\common\model\Ad as AdModel;
use app\common\model\Article;

class Ad extends AdminBase
{
    /**
     * 轮播管理列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }

    /**
     * 轮播列表JSON
     * @param string $limit 分页码
     */
    public function index_json($limit = '15')
    {
        $ad = new AdModel();
        $param = $this->request->param();
        $where = [];
        if (isset($param['name'])) {
            $ad = $ad->where('name','like',"%" . $param['name'] . "%");
        }
        if (isset($param['category'])) {
            $ad = $ad->where('category',$param['category']);
        }
        $list = $ad->with('category')->order('id desc')->where($where)->paginate($limit);
        $this->result($list);
    }

    /**
     * 添加轮播
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdModel::create($param);
            if ($result == true) {
                insert_admin_log('添加了广告');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save');
    }

    /**
     * 修改轮播页
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdModel::update($param,['id'=>$param['id']]);
            if ($result == true) {
                insert_admin_log('修改了广告');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save', ['data' => AdModel::where('id', input('id'))->find()]);
    }

    /**
     * 删除轮播页
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            AdModel::destroy($param['id']);
            insert_admin_log('删除了广告');
            $this->success('删除成功');
        }
    }
}
